package biz.yfsoft.app.fastframework.admin;

import biz.yfsoft.app.fastframework.core.Fast;
import biz.yfsoft.app.fastframework.plugin.IFastPlugin;
import biz.yfsoft.app.fastframework.plugin.IFastPlugin.Status;

import com.jfinal.kit.StrKit;


public class PluginController extends AdminController {
	
	@Override
	protected String getTable() {
		return "sys_plugin";
	}


	public void index() {
		render("/admin/system/plugin.jsp");
	}
	
	@Override
	protected String getSearchFields(String searchs) {
		if(isSqlInject(searchs)){
			return " 1 = 2 ";
		}
		
		if(searchs == null){
			return " 1 = 1 ";
		}
		return " name like '%{key}%' or title like '%{key}%' or class like '%{key}%' or args like '%{key}%' ".replace("{key}", searchs);
	}
	
	/**
	 * 获取插件的运行状态
	 */
	public void getStatus(){
		String plugin = getPara(0);
		if(StrKit.isBlank(plugin)){
			renderJson(wrapJson(-1,"未知的插件名!"));
			return;
		}
		if(!Fast.me().hasPlugin(plugin)){
			renderJson(wrapJson(-2,"未知的插件!"));
			return;
		}
		IFastPlugin fastPlugin = Fast.me().getPlugin(plugin);
		renderJson(wrapJson(0,fastPlugin.getStatus().toString()));
	}
	
	/**
	 * 启动插件
	 */
	public void startPlugin(){
		String plugin = getPara(0);
		if(StrKit.isBlank(plugin)){
			renderJson(wrapJson(-1,"未知的插件名!"));
			return;
		}
		if(!Fast.me().hasPlugin(plugin)){
			renderJson(wrapJson(-2,"未知的插件!"));
			return;
		}
		IFastPlugin fastPlugin = Fast.me().getPlugin(plugin);
		if(fastPlugin.getStatus() != Status.ACTIVED){
			if(fastPlugin.start()){
				//启动成功
				renderJson(wrapJson(0));
				return;
			}
		}
		renderJson(wrapJson(-3,"启动插件过程中发生了错误!"));
	}
	
	/**
	 * 停止插件
	 */
	public void stopPlugin(){
		String plugin = getPara(0);
		if(StrKit.isBlank(plugin)){
			renderJson(wrapJson(-1,"未知的插件名!"));
			return;
		}
		if(!Fast.me().hasPlugin(plugin)){
			renderJson(wrapJson(-2,"未知的插件!"));
			return;
		}
		IFastPlugin fastPlugin = Fast.me().getPlugin(plugin);
		if(fastPlugin.getStatus() == Status.ACTIVED){
			fastPlugin.stop();
		}
		//停止成功
		if(fastPlugin.getStatus() != Status.ACTIVED){
			renderJson(wrapJson(0));
			return;
		}
		renderJson(wrapJson(-3,"启动插件过程中发生了错误!"));
	}
	
}
